package cz.mendelu.swi2.catalogOfRobots;

import java.util.ArrayList;

/**
 * @author xvacula, xsafar1, xsmid
 * @version 1.0
 * @created 10-5-2012 9:36:00
 */
public class RobotRepository implements IRobotRepository {

	private static RobotRepository instance;
	private ArrayList<Robot> robots = new ArrayList<Robot>();
	public IWarehouse contains;
	public IUser m_IUser;



	public void finalize() throws Throwable {

	}

	private void RobotRepository() {
		
	}
	
	public static RobotRepository getInstance(){
		if (instance == null) {
			instance = new RobotRepository();
			fillTest(instance);
		}
		
		return instance;
	}

	private static void fillTest(RobotRepository instance) {
		//only for test
		Robot robot = createRobot();
		robot.setId(1);
		robot.setName("Robot 1");
		robot.setVersion("1.0");
		robot.setDescription("description Robot1");
		instance.addRobot(robot);
		
		robot = createRobot();
		robot.setId(2);
		robot.setName("Robot 2");
		robot.setVersion("1.0");

		robot.setDescription("description Robot2");
		instance.addRobot(robot);
		
		robot = createRobot();
		robot.setId(3);
		robot.setName("Robot 3");
		robot.setVersion("1.0");

		robot.setDescription("description Robot3");
		instance.addRobot(robot);
		
		robot = createRobot();
		robot.setId(4);
		robot.setName("Robot 4");
		robot.setVersion("1.0");

		robot.setDescription("description Robot4");
		instance.addRobot(robot);
		
		robot = createRobot();
		robot.setId(5);
		robot.setName("Robot 5");
		robot.setVersion("1.0");

		robot.setDescription("description Robot5");
		instance.addRobot(robot);
	}
	
	public void addRobot(Robot robot){
		
		if (getRobot(robot.getId()).getId() != 0) {
			deleteRobot(robot.getId());
		}
		
		robots.add(robot);
	}

	public static Robot createRobot(){
		return new Robot();
	}

	private Robot getRobotById(int id) {
		for (Robot robot : robots) {
			if (robot.getId() == id) {
				return robot;		
			}
		}
		return new Robot();
	} 
	
	public boolean deleteRobot(int id) {
		return robots.remove(getRobotById(id));
	}

	

	public Robot getRobot(int id){
		return getRobotById(id);
	}

	public ArrayList<Robot> getRobots(){
		return robots;
	}

	private int getId(Robot robot) {
		for (int i = 0; i < robots.size(); i++) {
			if (robot.getId() == robots.get(i).getId()) {
				return i;		
			}
		}
		return 1;
	}
	
	public void saveRobot(Robot robot){
		robots.set(getId(robot), robot);
	}
	
	public boolean checkRole(){
		//get role from user managament and check if it's teacher		
		return true;
	}

}